package com.ly.upload.web;

import com.ly.common.bean.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @program: ly-common
 * @description:
 * @author: 作者
 * @create: 2022-11-23 10:44
 */
@RestController
public class UploadController {

    @Value("${ly.upload.save-path}")
    private String savePath;

    @Value("${ly.upload.web-path}")
    private String webPath;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @PostConstruct
    public void init() {
        File file = new File(savePath);
        if (file.exists() == false) file.mkdirs();
        file = new File(webPath);
        if (file.exists() == false) file.mkdirs();
    }

    @RequestMapping(path = "delUld")
    public Result delUld(String path) throws IOException {
        path = path.replace(webPath,"");
        File filepath = new File(concat(savePath, path));
        if(filepath.delete()){
            return new Result(1,"文件删除成功！", null);
        } else {
            return new Result(0,"文件删除失败！", filepath.getAbsolutePath());
        }
    }

    @RequestMapping(path = "upload")
    public Result upload(@RequestParam(required = false) String path,
                         @RequestParam("file") MultipartFile... files) throws IOException {
        List<Object> list = new ArrayList<>();
        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            String suffix = null;
            if (filename.contains(".")) {
                suffix = filename.substring(filename.lastIndexOf(".") + 1);
            }
            filename = UUID.randomUUID().toString().replaceAll("-", "");
            filename += "." + suffix;
            File dir = new File(concat(savePath, path));
            if (dir.exists() == false) {
                dir.mkdirs();
            }
            File f = new File(dir, filename);
            logger.debug("文件保存至: "+f.getAbsoluteFile());
            file.transferTo(f);
            String desc = concat(webPath, path, filename);
            list.add(files.length > 1 ? build(file.getOriginalFilename(), desc) : build(desc));
        }
        return new Result(1, "文件上传成功!", list.size() == 1 ? list.get(0) : list);
    }

    private Object build(String descPath) {
        return descPath;
    }

    private Object build(String src, String desc) {
        Map<String, String> map = new HashMap<>();
        map.put("srcFile", src);
        map.put("descFile", desc);
        return map;
    }

    public static String concat(String... paths) {
        if (paths.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder(paths[0]);
        for (int i = 1; i < paths.length; i++) {
            if (paths[i] == null) continue;
            if (sb.charAt(sb.length() - 1) != '/' && !paths[i].startsWith("/")) {
                sb.append("/");
            }
            sb.append(paths[i]);
        }
        return sb.toString();
    }

}
